package com.andy.common.base

import android.app.Dialog
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.andy.common.utils.PhoneUtils
import com.andy.logcat.LogUtils
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import dp

/**
 * Author:Andy
 * Date:2023/8/23 12:07
 * Description:BaseBottomDialogFragment
 */
abstract class BaseBottomDialogFragment<VB : ViewBinding, VM : BaseViewModel> : BottomSheetDialogFragment() {

    protected open var mBehavior: BottomSheetBehavior<View>? = null
    protected open var mBinding: VB? = null
    protected open lateinit var mViewModel: VM

    abstract fun getViewBinding(): VB
    abstract fun getViewModel(): Class<VM>

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        mBinding = getViewBinding()
        mViewModel = ViewModelProvider(this)[getViewModel()]
        mBinding?.apply {
            dialog.setContentView(root)
            dialog.setCanceledOnTouchOutside(true)
            dialog.window?.setWindowAnimations(com.andy.base.R.style.BottomFragmentAnimation)
            mBehavior = BottomSheetBehavior.from((root.parent) as View)
            mBehavior?.skipCollapsed = true
            val pageHeight = getPageHeight()
            if (pageHeight > 0) {
                root.layoutParams.height = getPageHeight()
            }
            initObserve()
            initData()
            initAction()
        }
        return dialog
    }

    open fun getPageHeight(): Int {
        return PhoneUtils.screenHeight() - 30.dp
    }

    open fun initObserve() {}
    open fun initData() {}
    open fun initAction() {}

    override fun onStart() {
        super.onStart()
        val id = com.google.android.material.R.id.design_bottom_sheet
        val bottomSheet = dialog?.window?.findViewById<FrameLayout>(id)
        bottomSheet?.background = ColorDrawable(Color.TRANSPARENT)
        mBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
    }


    override fun show(manager: FragmentManager, tag: String?) {
        try {
            val ft = manager.beginTransaction()
            if (this.isAdded) {
                ft.remove(this)
            }
            ft.add(this, javaClass.name)
            ft.commitAllowingStateLoss()
        } catch (e: Exception) {
            LogUtils.e("errorMessage:${e.message}")
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        mBinding = null
        mViewModel.release()
    }
}